using MediatR;
using B.S.BasicData.Infrature;
using B.S.BasicData.Domain;
using B.S.BasicData.EroorCode;
using Microsoft.EntityFrameworkCore;

namespace B.S.BasicData.Api
{
    public class SlaughterInfoQueryHandler : IRequestHandler<SlaughterInfoQueryRequest, ApiResult<List<SlaughterInfoDto>>>
    {
        private readonly AppDbContext _context;

        public SlaughterInfoQueryHandler(AppDbContext context)
        {
            _context = context;
        }

        public async Task<ApiResult<List<SlaughterInfoDto>>> Handle(SlaughterInfoQueryRequest request, CancellationToken cancellationToken)
        {
            try
            {
                // 使用LINQ进行连表查询，根据生产批次(BatchNo)进行连接
                var query = from slaughter in _context.SlaughterInfos
                           join enterprise in _context.SlaughterEnterpriseInfos
                           on slaughter.BatchNo equals enterprise.BatchNo
                           select new SlaughterInfoDto
                           {
                               Id = slaughter.Id,
                               BatchNo = slaughter.BatchNo,
                               AverageWeight = slaughter.AverageWeight,
                               ArrivalTime = slaughter.ArrivalTime,
                               SlaughterTime = slaughter.SlaughterTime,
                               EnterpriseId = enterprise.Id,
                               CompanyName = enterprise.CompanyName,
                               CompanyAddress = enterprise.CompanyAddress,
                               CompanyDescription = enterprise.CompanyDescription,
                               EstablishmentDate = enterprise.EstablishmentDate
                           };

                // 如果指定了生产批次，则进行筛选
                if (!string.IsNullOrWhiteSpace(request.BatchNo))
                {
                    query = query.Where(x => x.BatchNo == request.BatchNo);
                }

                var result = await query.ToListAsync(cancellationToken);

                return ApiResult<List<SlaughterInfoDto>>.Success(result, "查询成功");
            }
            catch (Exception ex)
            {
                return ApiResult<List<SlaughterInfoDto>>.Fail($"查询失败: {ex.Message}", ApiResultCode.Error);
            }
        }
    }
} 